package com.rich.dao.impl;

import java.sql.SQLException;

import javax.management.Query;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.rich.dao.UserDao;
import com.rich.domain.User;
import com.rich.utils.DataSourceUtils;

public class UserDaoImpl implements UserDao {

	QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
	/**
	 * 用户注册
	 * @throws SQLException 
	 */
	@Override
	public void save(User user) throws SQLException {
		String sql = "INSERT INTO user VALUES(?,?,?,?,?,?,?,?,?,?)";
		qr.update(sql, user.getUid(),user.getUsername(),user.getPassword(),
				user.getName(),user.getEmail(),user.getTelephone(),user.getBitthday(),
				user.getSex(),user.getState(),user.getCode());
	}

	/**
	 * 根据code获取用户
	 */
	@Override
	public User getByCode(String code) throws Exception {
		String sql = "SELECT * FROM user WHERE code=? LIMIT 1";
		return qr.query(sql, new BeanHandler<>(User.class), code);
	}

	/**
	 * 更新用户
	 */
	@Override
	public void update(User user) throws Exception {
		String sql = "UPDATE user SET password = ?,sex = ?,state = ?,code = ? WHERE uid = ?";
		qr.update(sql, user.getPassword(),user.getSex(),user.getState(),user.getCode(),user.getUid());
	}

	/**
	 * 获取登陆信息
	 */
	@Override
	public User getUser(String userName, String password) throws Exception {
		String sql = "SELECT * FROM user WHERE username = ? AND password = ? LIMIT 1";
		return qr.query(sql, new BeanHandler<>(User.class), userName,password);
	}	
}
